package cc.linker.steplink.crm.commons.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.*;

@Slf4j
public class SignUtils {

    public static String generateSignature(Map<String, Object> apiParam, String secret) {
        Set<String> keySet = apiParam.keySet();
        List<String> paramNames = new ArrayList<String>(keySet);

        Collections.sort(paramNames);

        StringBuilder paramNameValue = new StringBuilder();

        for (String paramName : paramNames) {
            if("sign".equals(paramName)){
                continue;
            }

            Object param = apiParam.get(paramName);
            if (param == null) {
                continue;
            }

            if (StringUtils.isBlank(param + "")) {
                continue;
            }

            paramNameValue.append(paramName).append(apiParam.get(paramName));
        }

        String source = secret + paramNameValue.toString() + secret;
        return MD5.encode(source).toUpperCase();
    }
    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data Map类型数据
     * @param key API密钥
     *
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isNotifySignValid(Map<String, Object> data, String key) throws Exception {
        if (!data.containsKey("sign") ) {
            return false;
        }
        String sign = data.get("sign").toString();
        return generateSignature(data, key).equals(sign);
    }

}
